package com.wang.controller_wifi.manager;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;

public class WifiManager {
	
	private static WifiManager manager;
	
	private HandlerThread thread;
	private Handler handler;
	private Handler notifyHandler;
	private HandleAction action;
	private List<NotifyListener> listeners = new ArrayList<NotifyListener>();
	private Context context;
	
	private WifiManager(Context ctx){
		this.context = ctx;
		action = new HandleAction(ctx, this);
		notifyHandler = new NotifyHandler();
		init();
	}
	
	private void init(){
		thread = new HandlerThread("bluetoothController");
		thread.setPriority(Thread.MAX_PRIORITY);
		thread.start();
		handler = new MyHandler(thread.getLooper());
	}
	
	public static WifiManager getInstance(Context ctx){
		
		if(manager == null){
			manager = new WifiManager(ctx);
		}
		
		return manager;
	}
	
	public void connect(){
		handler.obtainMessage(Constant.ACTION_CONNECT).sendToTarget();
	}
	
	public void drive(){
		handler.obtainMessage(Constant.ACTION_CMD, "u").sendToTarget();
	}
	
	public void back(){
		handler.obtainMessage(Constant.ACTION_CMD, "t").sendToTarget();
	}
	
	public void left(){
		handler.obtainMessage(Constant.ACTION_CMD, "l").sendToTarget();
	}
	
	public void right(){
		handler.obtainMessage(Constant.ACTION_CMD, "r").sendToTarget();
	}
	
	public void sendCmd(String cmd){
		handler.obtainMessage(Constant.ACTION_CMD, cmd).sendToTarget();
	}
	
	public void stop(){
		handler.obtainMessage(Constant.ACTION_CMD, "s").sendToTarget();
	}
	
	public void interrupt(){
		action.isInterrupt = true;
	}
	public void register(NotifyListener listener){
		listeners.add(listener);
	}
	
	public void unregister(NotifyListener listener){
		listeners.remove(listener);
	}
	
	public void notifyMessage(int what){
		notifyHandler.obtainMessage(what).sendToTarget();
	}
	
	private class NotifyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case Constant.NOTIFY_CONNECT_SUCCESS:
				for(NotifyListener listener: listeners){
					listener.onConnectSuccess();
				}
				break;
			case Constant.NOTIFY_CONNECT_FAIL:
				for(NotifyListener listener: listeners){
					listener.onConnectFail();
				}
				break;
			}
		}
	}
	
	private class MyHandler extends Handler{

		public MyHandler(Looper l){
			super(l);
		}
		@Override
		public void handleMessage(Message msg) {
			action.handle(msg);
		}
	}
	
	
	
}
